package com.tnsw.noxnox.downloader;

import java.util.Hashtable;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class DownloaderService implements GCMReceiverInterface {

	private static boolean sIsRunning = false;
	private static DownloaderService sInstance;
	
	private String tag = "DownloaderService";
	private Context context;
	
	private Hashtable<Integer, DLBase> hashDls;
	
	public DownloaderService(Context context) {
		Log.d(tag, "Constructor(context)");
		this.context = context;
		this.hashDls = new Hashtable<Integer, DLBase>();
		sIsRunning = true;
	}
	
	public static DownloaderService getInstance(Context context) {
		if (sIsRunning == false) {
			sInstance = new DownloaderService(context);
		}
		
		return(sInstance);
	}
	
	@Override
	public void onReceiveMessage(Intent intent) {
		Log.d(tag, "Received Message");
		if (intent != null) {
			Bundle extras = intent.getExtras();
			if (extras.containsKey("key") == true) {
				if (extras.getString("key").equals("url")) {
					if (extras.containsKey("value")) {
						String url = extras.getString("value");
						this.doDownload(url);
					}
				}
			}
		}
	}
	
	public void doDownload(String url) {
		Log.d(tag, "doDownload(" + url + ")");
		try {
			boolean found = true;
			
			Uri uri = Uri.parse(url);
			String hostL = uri.getHost().toLowerCase();
			DLBase dl = null;
			if (hostL.equals("www.youtube.com")) {
				dl = new YoutubeDL(this.context, url);
				dl.doit();
				
			} else if (hostL.equals("www.dailymotion.com")) {
				dl = new DailyMotionDL(this.context, url);
				dl.doit();
				
			} else {
				Log.d(tag, "Not found engine");
				found = false;
			}
			
			if (found == true) {
				Log.d(tag, "Found Engine");
				this.hashDls.put(dl.dp.primarykey, dl);
				Log.d(tag, "Added dp.primarykey=" + dl.dp.primarykey + " into hashDls");
			}			
		} catch (Exception e) {
			Log.e(tag, "doDownload - " + e.toString(), e);
		}

	}
	
	public void registerDLInterface(int primarykey, DLInterface dli) {
		//Log.d(tag, "calling registerDLinteface(primarykey=" + primarykey + ")");
		DLBase dl = null;
		dl = this.hashDls.get(primarykey);
		if (dl != null) {
			dl.setDLInterface(dli);
			//Log.d(tag, "> registered");
		} else {
			//Log.d(tag, "> Not found");
		}
	}
	
	public DLBase getDLBase(int primaryKey) {
		return(this.hashDls.get(primaryKey));
	}

}
